// var time_gap = ['7:00-7:30', '7:30-8:00', '8:00-8:30', '8:30-9:00', '9:00-9:30', '9:30-10:00', '10:00-10:30', '10:30-11:00', '11:00-11:30', '11:30-12:00', '12:00-12:30'];
var time_gap = [
    "00:00-00:30", "00:30-01:00", "01:00-01:30", "01:30-02:00", "02:00-02:30", "02:30-03:00",
    "03:00-03:30", "03:30-04:00", "04:00-04:30", "04:30-05:00", "05:00-05:30","05:30-06:00",
    "06:00-06:30", "06:30-07:00", "07:00-07:30", "07:30-08:00", "08:00-08:30", "08:30-09:00",
    "09:00-09:30", "09:30-10:00", "10:00-10:30", "10:30-11:00", "11:00-11:30", "11:30-12:00",
    "12:00-12:30","12:30-13:00", "13:00-13:30", "13:30-14:00", "14:00-14:30", "14:30-15:00",
    "15:00-15:30", "15:30-16:00", "16:00-16:30", "16:30-17:00", "17:00-17:30", "17:30-18:00",
    "18:00-18:30", "18:30-19:00", "19:00-19:30","19:30-20:00", "20:00-20:30", "20:30-21:00",
    "21:00-21:30", "21:30-22:00", "22:00-22:30", "22:30-23:00", "23:00-23:30", "23:30-24:00"
];
// for(var i=0;i<24;i++){
//     for(var j =0;j<2;j++){
//         var hour = i<10?('0'+i):(i+'');
//         var minute = (j*30)===0?('0'+j*30+''):(j*30+'');
//         var time = hour + ':'+ minute;
//         time_gap.push(time);
//     }
// }
airRidePoint = {
    chart1: null,
    chart2: null,
    table: null,
    init: function () {
        initTime();
        setInterval(initTime, 1000 * 10);
        initChart1Data();
        initChart2Data();
        initTableData();
    },
    initTable: function () {
        airRidePoint.table = initTable();
    }
};

// 初始化-专线车辆图表
var initChart1Data = function () {
    console.log("initChart1...");
    airRidePoint.chart1 = echarts.init(document.getElementById('carChart'));
    airRidePoint.chart1.setOption(getEchart1Option());
    setInterval(function () {
        airRidePoint.chart1.setOption(getEchart1Option())
    }, 1000 * 10);
};

// 初始化-人数比较图表
var current_point_id = '-1';
var initChart2Data = function () {
    console.log("initChart2...");
    // 获取首个乘车点
    var $firstPoint = $("#pointSelect ul li").eq(0);
    $("#pointSelect>span").html($firstPoint.html());
    // 设定当前乘车点
    // var current_point_id = $firstPoint.data("id");
    airRidePoint.chart2 = echarts.init(document.getElementById('personChart'));
    airRidePoint.chart2.setOption(getEchart2Option(current_point_id));
    setInterval(function () {
        airRidePoint.chart2.setOption(getEchart2Option(current_point_id))
    }, 1000 * 10);
};

// 初始化-数据表格
var current_index;
var current_trip_id=1;
var initTableData = function () {
    console.log("initTable...");
    // 获取首条专线
    var $firstTrip = $("#tripSelect ul li").eq(0);
    $("#tripSelect>span").html($firstTrip.html());
    $("#tripSelect>span em").eq(0).attr({
        "class": "show-pointinfo",
        "data-pointid": $firstTrip.data("id")
    })
    // 设定当前专线
    // current_trip_id = $firstTrip.data("id");
    updateTable(current_trip_id);
    setInterval(function () {
        updateTable(current_trip_id)
    }, 1000 * 10);
};

var initTime = function () {
    var today = new Date();
    var hour = today.getHours();
    var minutes = today.getMinutes();
    var time_current = hour + ":00-" + (hour === 24 ? 0 : (hour + 1)) + ":00";
    var time_current_next = (hour === 24 ? 0 : (hour + 1)) + ":00-" + ((hour + 1) === 24 ? 0 : (hour + 2)) + ":00";
    var current_date = (today.getMonth() + 1) + "月" + today.getDate() + "日";
    $(".current_date").html(current_date);
    $(".time_current").html(time_current);
    $(".time_current_next").html(time_current_next);
    current_index = 2 * hour;
    if (minutes > 30) {
        current_index++;
    }
};

var updateTime = function () {
    var today = new Date();
    var hour = today.getHours();
    var minutes = today.getMinutes();
    $("#time").html(hour+":"+minutes);
}

// 更新数据表格
var updateTable = function (id) {
    // updateTime();
    airRidePoint.initTable();
    var param = {airRidePointId: id};
    $.ajax({
        url: "getAvgConsume.do",
        data: param,
        type: "GET",
        success: function (data) {
            var result = data.data;
            var backing = result.backing;
            var backing_next = result.backing_next;
            var backing_seat=0,backing_next_seat=0;
            for(var b in backing){
                backing_seat += backing[b].seating;
            }
            for(var b in backing_next){
                backing_next_seat += backing_next[b].seating;
            }
            $("#backing").html(backing.length+"辆");
            $("#backing").next().html(backing_seat+"座");
            $("#backing_next").html(backing_next.length+"辆");
            $("#backing_next").next().html(backing_next_seat+"座");


            $("#go_time").html(result.go_time>0?(result.go_time+"分钟"):"-");
            $("#back_time").html(result.back_time>0?(result.back_time+"分钟"):"-");
        }
    });
    $.ajax({
        url: "getLeastConsume.do",
        data: param,
        type: "GET",
        success: function (data) {
            var result = data.data;
            $("#least_go_time").html(result.least_go_time>0?(result.least_go_time+"分钟"):"-");
            $("#least_back_time").html(result.least_back_time>0?(result.least_back_time + "分钟"):"-");
        }
    });
    $.ajax({
        url: "getCarByPointId.do",
        data: param,
        type: "GET",
        success: function (data) {
            var carList = data.data;
            var seatSum = 0;
            for (var c in carList) {
                var car = carList[c];
                var i = car.status;
                var seat = car.seating;
                if(seat){
                    seatSum += seat;
                }
                if (i > 0) {
                    airRidePoint.table[i - 1]["value"]++;
                    airRidePoint.table[i - 1]["seat"] += seat;
                }
            }
            $(".waitCar").html(airRidePoint.table[0]["value"] + '辆');
            $(".waitCar").next().html(airRidePoint.table[0]["seat"]+"座");

            $(".ridingCar").html(airRidePoint.table[1]["value"] + '辆');
            $(".ridingCar").next().html(airRidePoint.table[1]["seat"]+"座");

            $(".returningCar").html(airRidePoint.table[2]["value"] + '辆');
            $(".returningCar").next().html(airRidePoint.table[2]["seat"]+"座");

            $(".returnedCar").html(airRidePoint.table[3]["value"] + '辆');
            $(".returnedCar").next().html(airRidePoint.table[3]["seat"]+"座");
            $(".carSum_table").html(carList.length + '辆');
            $(".seatSum").html(seatSum + '座');
        }
    });
    $.ajax({
        url: "getTableData.do",
        data: param,
        type: "GET",
        success: function (data) {
            var result = data.data;
            var appointSum = 0, tookSum = 0;//该乘车点
            var dto = result.dto;
            appointSum = dto.appointSum;
            tookSum = dto.tookSum;
            $("#table_appointSum").html(appointSum);
            $("#table_tookSum").html(tookSum);
        }
    });
    var time = "";
    var waitingSum = 0;
    $.ajax({
        url: "getLeastRecord.do",
        data: param,
        async:false,
        type: "GET",
        success: function (data) {
            if(data.code==200){
                var note = data.data.note;
                if (data) {
                    waitingSum = note.replace(/[^0-9]/ig,"");
                    var d = new Date(data.data.feedbackDate);
                    time = dateFtt("hh:mm:ss", d);
                    time = '(' + time + ')';
                    console.log(data);
                }
            }
        }
    });
    $("#time").html(time);
    $("#table_waitingSum").html(waitingSum);
};

var initTable = function () {
    var table_data = [
        {"name": "等待发车", "value": 0, "seat": 0},
        {"name": "已发车", "value": 0, "seat": 0},
        {"name": "已到达", "value": 0, "seat": 0},
        {"name": "已返程", "value": 0, "seat": 0}
    ];
    return table_data;
};

// 车辆图表
var getEchart1Option = function () {
    var chart1 = [
        {"name": "等待发车", "value": 0},
        {"name": "已发车", "value": 0},
        {"name": "已到达", "value": 0},
        {"name": "已返程", "value": 0}
    ];
    var url = "getAllCar.do";
    $.ajax({
        url: url,
        type: "GET",
        async: false,
        success: function (result) {
            var carList = result.data;
            for (var c in carList) {
                var car = carList[c];
                if (car.status > 0) {
                    var i = car.status;
                    chart1[i - 1]["value"]++;
                }
                $(".carSum").html(carList.length);
            }
        }
    });

    var option = {
        tooltip: {
            trigger: 'item',
            // formatter: "{b} : {c} 辆"
            formatter: function (a) {
                var tipHtml = '<div class="chart-tip">' +
                        '<span>' + a.name + '</span>'+
                        '<p>' + a.value + ' 辆</p>'+
                    '</div>';
                return tipHtml
            },
            backgroundColor: 'transparent',
            padding: 0
        },
        visualMap: {
            show: false,
            color: ['#46cefb', '#32bbe8', '#25aad6', '#0f98c5']
        },
        series: [{
            type: 'pie',
            radius: '65%',
            center: ['50%', '55%'],
            data: chart1.sort(function (a, b) {
                return a.value - b.value;
            }),
            minAngle: 20,
            roseType: 'radius',
            clockwise: false,
            label: {
                normal: {
                    formatter: '{c}\n{b}',
                    textStyle: {
                        color: '#ffffff',
                        fontFamily: 'Microsoft yahei',
                        fontSize: 15,
                        lineHeight: 24
                    }
                }
            },
            labelLine: {
                normal: {
                    lineStyle: {
                        color: '#4cd3ff',
                        opacity: 0.6
                    },
                    smooth: 0.2,
                    length: 10,
                    length2: 20
                }
            },
            itemStyle: {
                normal: {
                    shadowBlur: 56,
                    shadowColor: 'rgba(21, 93, 116, 0.4)'
                }
            },
            animationType: 'scale',
            animationEasing: 'elasticOut',
            animationDelay: function (idx) {
                return Math.random() * 200;
            }
        }]
    };
    return option;
};

// 人数图表
var getEchart2Option = function (val) {
    var url = "getRidePointBarData.do";
    var param = {airRidePointId: val};
    var chart2_1 = [];//候车
    var chart2_2 = [];//发车
    for(var a in time_gap){
        chart2_1.push(0);
        chart2_2.push(0);
    }

    $.ajax({
        url: url,
        type: "GET",
        async: false,
        data: param,
        success: function (result) {
            var appointSum = 0, tookSum = 0, waitingSum = 0;//该乘车点
            var airCarRecordTimeList = result.data.airCarRecordList;
            var airRidePointDtoList = result.data.airRidePointDtoList;
            // var back_tookSum = result.data.tookSum;
            // if(back_tookSum){
            //     tookSum = back_tookSum;
            // }
            for (var a in airCarRecordTimeList) {//该乘车点或者所有乘车点的记录
                if(airCarRecordTimeList[a]) {
                    var index = time_gap.indexOf(a);
                    if(index>-1) {
                        for (var r in airCarRecordTimeList[a]) {
                            var record = airCarRecordTimeList[a][r];
                            // if (record.status === '2' || record.status === 2) {
                            chart2_2[index] += record.passengerSum;
                            // }
                        }
                    }
                }
            }
            for (var c in chart2_2) {
                tookSum += chart2_2[c];
            }
            for (var d in airRidePointDtoList) {
                var dto = airRidePointDtoList[d];
                if (val !== '' && val !== -1 && val !== '-1') {//该乘车点
                    if (dto.airRidePoint.id == val) {
                        waitingSum = dto.airRidePoint.waitingSum;
                        appointSum = dto.appointSum;
                    }
                } else {
                    waitingSum += dto.airRidePoint.waitingSum;
                    appointSum += dto.appointSum;
                }
            }
            if (current_index >= 0 && current_index < time_gap.length) {
                chart2_1[current_index] = waitingSum;
            }
            $("#chart_appointSum").html(appointSum);
            $("#chart_tookSum").html(tookSum);
        }
    });
    option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow',
                shadowStyle: {
                    color: new echarts.graphic.LinearGradient(
                        0, 0, 0, 1,
                        [
                            {offset: 0, color: 'rgba(255,255,255,.1)'},
                            {offset: 1, color: 'rgba(255,255,255,0)'}
                        ], false)
                }
            },
            formatter: function (a) {
                var tipHtml = '<div class="chart-tip"><span>' + a[0].axisValue + '</span>';
                for (var i = 0; i < a.length; i++) {
                    tipHtml += '<p>' + a[i].seriesName + '： ' + a[i].value + ' 人</p>';
                }
                tipHtml += '</div>';
                return tipHtml
            },
            backgroundColor: 'transparent',
            padding: 0
        },
        legend: {
            show: false,
            data: ['候车人数', '已运送人数']
        },
        grid: {
            show: true,
            left: 0,
            right: 10,
            bottom: 10,
            top: 10,
            containLabel: true,
            backgroundColor: 'rgba(0,0,0,0.2)',
            borderWidth: 0
        },
        xAxis: [
            {
                type: 'category',
                data: time_gap,
                axisTick: {show: false},
                axisLabel: {
                    fontSize: 14,
                    color: '#ffffff'
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#236386'
                    }
                },
                splitLine: {
                    show: false
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                axisTick: {show: false},
                axisLabel: {
                    fontSize: 12,
                    color: '#95a9bb'
                },
                axisLine: {
                    show: false
                },
                splitLine: {
                    show: true,
                    lineStyle: {
                        color: '#236386'
                    }
                }
            }
        ],
        series: [
            {
                name: '候车人数',
                type: 'bar',
                // data: [320, 332, 301, 334, 390, 100, 122, 144, 555, 33, 55],
                data: chart2_1,
                barWidth: 8,
                smooth: true,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(
                        0, 0, 0, 1,
                        [
                            {offset: 0, color: '#fff799'},
                            {offset: 1, color: '#fcbc71'}
                        ], false),
                    barBorderRadius: [10, 10, 0, 0]
                }
            },
            {
                name: '已运送人数',
                type: 'bar',
                // data: [150, 232, 201, 154, 190, 200, 150, 100, 50, 30, 20],
                data: chart2_2,
                barWidth: 8,
                smooth: true,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(
                        0, 0, 0, 1,
                        [
                            {offset: 0, color: '#4cfff4'},
                            {offset: 1, color: '#4cd3ff'}
                        ], false),
                    barBorderRadius: [10, 10, 0, 0]
                }
            }
        ]
    };
    return option;
};

// 图表自适应浏览器尺寸
window.onresize = function () {
    airRidePoint.chart1.resize();
    airRidePoint.chart2.resize();
};


